package com.hefan.api.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.cat.common.entity.Page;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.common.meta.UserTypeEnum;
import com.cat.common.meta.WebUserCachTypeEnum;
import com.hefan.api.bean.LoginUserVo;
import com.hefan.common.point.bean.BuriedPointVo;
import com.hefan.live.bean.LiveRoom;
import com.hefan.live.itf.LiveRoomService;
import com.hefan.notify.itf.ImUserService;
import com.hefan.notify.itf.MessageService;
import com.hefan.oms.itf.AnchorTicketMonthService;
import com.hefan.user.bean.HfUserPreInit;
import com.hefan.user.bean.WebUser;
import com.hefan.user.bean.WebUserIdentity;
import com.hefan.user.itf.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.profiler.Profiler;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户信息
 * Created by lxw on 2016/9/26.
 */
@Component
public class UserLocalService {

    private Logger logger = LoggerFactory.getLogger(UserLocalService.class);

    @Reference
    private WebUserService webUserService;

    @Reference
    private UserCacheService userCacheService;

    @Reference
    private UserSequenceService userSequenceService;

    @Reference
    private UserIdentityService userIdentityService;

    @Reference
    private MessageService messageService;

    @Reference
    private ImUserService imUserService;

    @Reference
    private LiveRoomService liveRoomService;

    @Reference
    AnchorTicketMonthService anchorTicketMonthService;

    @Reference
    private WebUserAccountService webUserAccountService;

    /**
     * 用户登陆的属性检查
     * @param webUser
     * @return
     */
    public ResultBean userLoginPubCheck(WebUser webUser) {
        if(webUser == null) {
            return new ResultBean(ResultCode.LoginUserAgain,null);
        }
        if(webUser.getState() !=0 || webUser.getSuperiorState() !=0) { //判断是否冻结
            return new ResultBean(ResultCode.LoginUserIsLock,null);
        }
        return new ResultBean(ResultCode.SUCCESS,null);
    }

    /**
     * 根据userId获取用户基础信息
     * @param userId
     * @return
     */
    @Transactional(readOnly = true)
    public WebUser getWebUserByUserId(String userId) {
        return webUserService.getWebUserInfoByUserId(userId);
    }

    /**
     * 根据多个用户id获取用户基本信息列表
     * @param userIdList
     * @return
     */
    @Transactional(readOnly = true)
    public ResultBean queryUserInfoByUserIdList(List userIdList) {
        return webUserService.getWebUserInfoByUserIdList(userIdList);
    }

    /**
     * 根据第三方信息获取用基本信息
     * @param thridType 1 微博   2 微信  3 qq  4 手机号
     * @param thridOpendId
     * @return
     */
    @Transactional(readOnly = true)
    public WebUser getWebUserInfoByThridParty(int thridType, String thridOpendId) {
        return webUserService.getWebUserInfoByThridParty(thridType, thridOpendId);
    }

    /**
     * 进行自动注册
     * @param webUser
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ResultBean<WebUser> saveRegisterUserInfo(WebUser webUser, int thridType,String account) {
        Profiler profiler = new Profiler("-----saveRegisterUserInfo-----");
        ResultBean<WebUser> resultBean = new ResultBean(ResultCode.SUCCESS,null);
        profiler.start("-----获取用户userId-----");
        long userIdLong = userSequenceService.getNextSeqVal(0);
        if(userIdLong == 0) {
            return null;
        }
        webUser.setUserId(String.valueOf(userIdLong));
        profiler.start("-----获取用户IM_TOKEN-----");
        //获取向IM中注册并获取IM_TOKEN
        //String imToken = createrImToken(webUser);
        String imToken = getImTokenOprate(webUser);
        if(StringUtils.isBlank(imToken)) {
            return new ResultBean<WebUser>(ResultCode.LoginUserRegistImError,null);
        }
        webUser.setImToken(imToken);
        profiler.start("-----新增用户保存-----");
        webUser = webUserService.saveRegisterUserInfo(webUser,thridType,account);
        profiler.stop().print();
        resultBean.setData(webUser);
        return resultBean;
    }

    /**
     * 先由初始化表中获取imToken,不存在时请求第三方获取imToken
     * @param webUser
     * @return
     */
    public String getImTokenOprate(WebUser webUser) {
        String imToken = null;
        HfUserPreInit hfUserPreInit = webUserService.getUserPreInit(webUser.getUserId());
        if(hfUserPreInit == null || StringUtils.isBlank(hfUserPreInit.getImToken())) {
            //请求第三方获取IM的token
            imToken = createrImToken(webUser);
        } else {
            imToken = hfUserPreInit.getImToken();
        }
        return imToken;
    }

    /**
     * 获取imToken信息
     * @param webUser
     * @return
     */
    private String createrImToken(WebUser webUser) {
        String imToken = null;
        int runNum = 0;
        try {
            while (StringUtils.isBlank(imToken) && runNum < 3) {
                runNum++;
                if (StringUtils.isBlank(webUser.getNickName())) {
                    webUser.setNickName(webUser.getUserId());
                }
                //获取imToken
                ResultBean imResBean = imUserService.createUser(webUser.getUserId(), webUser.getNickName(), "", "", "");
                if (imResBean.getCode() == ResultCode.SUCCESS.get_code()) {
                    imToken = String.valueOf(imResBean.getData());
                }else if(imResBean.getCode() == ResultCode.ImAlreadyRegistered.get_code()) {
                    //重新刷新imToken
                    imToken = refresImToken(webUser.getUserId());
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
        return imToken;
    }

    /**
     * 根据用户userId刷新imToken
     * @param userId
     * @return
     */
    private String refresImToken(String userId) {
        String imToken = null;
        ResultBean imResBean = imUserService.refreshToken(userId);
        if(imResBean.getCode() == ResultCode.SUCCESS.get_code()) {
            imToken = String.valueOf(imResBean.getData());
        }
        return imToken;
    }

    /**
     * 绑定|解绑用户账户信息[微博|微信|QQ|手机号]（不进行手机号解绑）
     * @param userId
     * @param opFlag 1 绑定   2 解绑
     * @param loginUserVo
     * @return
     */
    public ResultBean accountSafeOpreate(String userId, int opFlag, LoginUserVo loginUserVo) {
        ResultBean resultBean = webUserService.userAccountSafeOprate(userId, opFlag, loginUserVo.getThirdType(), loginUserVo.getOpenid(),
                loginUserVo.getHeadImg(), loginUserVo.getNickName(), loginUserVo.getQq(),loginUserVo.getUnionidWx());
        return resultBean;
    }

    /**
     * 根据用户userId更新用户基本信息
     * @param webUser
     * @return
     */
    public ResultBean updateUserBaseInfo(WebUser webUser) {
        return webUserService.updateWebUserBaseInfo(webUser);
    }

    /**
     * 用户申请主播认证提交
     * @param webUserIdentity
     * @return
     */
    public ResultBean userIndentitySubmit(WebUserIdentity webUserIdentity) {
        return userIdentityService.saveUserIndentity(webUserIdentity);
    }


    /**
     * 获取申请主播认证填写的开户行列表信息
     * @return
     */
    public ResultBean findSysBankList() {
        return userIdentityService.findSysBankList();
    }

    /**
     * 增加用户的饭票数
     * @param userId
     * @param incrBalance
     * @return
     */
    public int incrWebUserBalance(String userId, long incrBalance){
        return  webUserService.incrWebUserBalance(userId, incrBalance);
    }

    /**
     * 将缓存中的盒饭历史数更新到数据库中
     * @param userId
     */
    @Async
    public void incrWebUserHefanFromCach(String userId) {
        try {
            webUserService.incrWebUserHefanFromCach(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取我的信息
     * @param userId
     * @return
     */
    public ResultBean findMyUserInfo(String userId) {
        Map resMap = new HashMap();
        WebUser webUser = webUserService.findMyUserInfo(userId);
        if(webUser != null) {
            //是主播
            if(UserTypeEnum.isAnchor(webUser.getUserType())) {
                //获取主播live_room信息
                LiveRoom liveRoom = liveRoomService.getLiveRoom(userId);
                resMap.put("liveRoom",liveRoom);
            }
        }
        resMap.put("webUser",webUser);
        return new ResultBean(ResultCode.SUCCESS,resMap);
    }
    /**
     * 根据用户id获取相关推荐的主播信息
     * @param userId
     * @return
     */
	public List recommendAnchorFirst(String userId) {
		return userCacheService.recommendAnchorFirstCache(userId);
	}
	
	/**
	 * h5页面主播排行榜
	 * @param page
	 * @param userId
   * @param type 0 积分，1盒饭排行榜
   * @return
	 */
  public Page getAnchorRankingList(Page page, String userId, int type) throws Exception {
        return webUserService.getAnchorRankingList(page, userId, type);
  }


    /**
     * 主播排行榜新需求实现
     * @param page
     * @param type
     * @return
     * @throws Exception
     */
    public Page getAnchorRankingList2(Page page, int type) throws Exception {
        return webUserService.getAnchorRankingList2(page, type);
    }
	
	/**
	 * 推荐明星俱乐部
	 * @param page
	 * @param userId
	 * @return
	 */
	public Page recommendStarClub(Page page, String userId) {
		return webUserService.recommendStarClub(page, userId);
		
	}

	/**
	 * 更新用户定位信息
	 * @param userId
	 * @param gpsLocation
	 */
	public void updateWebUserLocation(String userId, String gpsLocation) {
		webUserService.updateWebUserLocation(userId,gpsLocation);
	}

    /**
     * 获取用户可用盒饭数
     * @param userId
     * @return
     */
    public long getWebUserValidHeFanCount(String userId) {
       return anchorTicketMonthService.selectAvailableTickets(userId);
    }

    /**
     * 获取普通用户的可用盒饭数
     * @param userId
     * @return
     */
    public long getCommonUserValidHeFanCount(String userId) {
        return webUserAccountService.getBaseUserIncome(userId);
    }

    /**
     * 获取用户基本信息和认证信息 包含粉丝和关注数
     * @param userId
     * @return
     */
    public Map getUserInfoAndIdentity(String userId) {
        WebUser webUser = webUserService.findMyUserInfo(userId);
        WebUserIdentity webUserIdentity = userIdentityService.getUserIndentityInfo(userId);
        Map resMap = new HashMap();
        resMap.put("webUser",webUser);
        resMap.put("webUserIdentity", webUserIdentity == null ? new WebUserIdentity() : webUserIdentity);
        return resMap;
    }

    /**
     * 修改用户简介信息|昵称
     * @param paramsMap
     * @return
     */
    public ResultBean modifyUserPersionalProfile(Map paramsMap) {
        return userIdentityService.modifyUserPersionalProfile(paramsMap);
    }


    public ResultBean findUserByUserId(String userId) {
        ResultBean res = new ResultBean(ResultCode.SUCCESS,null);
        try{
            WebUser webUser = webUserService.findUserInfoFromCache(userId);
            if(webUser == null){
                return new ResultBean(ResultCode.LoginUserIsNotExist,null);
            }
            res = userLoginPubCheck(webUser);
        }catch(Exception e){
            e.printStackTrace();
            return new ResultBean(ResultCode.LoginUserIsNotExist,null);
        }
        return res;
    }

    /**
     * 由缓存中获取用户信息
     * @param userId
     * @return
     */
    public WebUser findUserInfoFromCache(String userId) {
        WebUser webUser = null;
        try{
            webUser = webUserService.findUserInfoFromCache(userId);
        }catch(Exception e){
            e.printStackTrace();
        }
        return webUser;
    }

    /**
     * 微信登录处理（老版本微信登录的opendid错误问题）
     * @return
     */
    public ResultBean handleWebUserByWxUid(WebUser webUser, LoginUserVo loginUserVo, BuriedPointVo buriedPointVo) {
        if(webUser == null) {
           if(StringUtils.isNotBlank(loginUserVo.getWxuid())) {
               webUser = webUserService.getWebUserInfoByThridParty(loginUserVo.getThirdType(),loginUserVo.getWxuid());
               if(webUser != null) {
                   //将表中wxuid变更为wxopenid
                   int resutCode = webUserService.modifyWebUserInfoNewWxOpenId(webUser.getUserId(),loginUserVo.getOpenid());
                   if(resutCode == 1) {
                       webUser.setOpenidWx(loginUserVo.getOpenid());
                   } else { //如果新wxopenid在数据库中存在，则提示客户微信openid异常请联系客服人员
                        return new ResultBean(ResultCode.ThridUserWxError,null);
                   }
               }
           }
        }
        if(webUser == null && buriedPointVo == null) { //用户不存在，并且head头对象不存在，提示用户进行版本升级，不能进行新用户注册
            return new ResultBean(ResultCode.ThridUserVersionError,null);
        }
        return new ResultBean(ResultCode.SUCCESS,webUser);
    }

    /**
     * 更新用户的unionidWx
     * @param userId
     * @param unionidWx
     */
    public void updateWebUserUnionidWx(String userId, String unionidWx) throws Exception {
        webUserService.updateWebUserUnionidWx(userId,unionidWx);
    }

    /**
     * 用户缓存测试
     * @param userId
     * @param cachType
     * @param icrVal
     * @return
     */
    public Map userCachOpTest(String userId, int cachType, long icrVal) {
        Map resMap =  new HashMap();
        if(WebUserCachTypeEnum.Exp_type.getType() == cachType) {
            ResultBean res = webUserService.userLevelOprate(userId,icrVal);
            resMap.put("incrRest",res);
        } else if(WebUserCachTypeEnum.Balance_type.getType() == cachType) {
            int res = webUserService.incrWebUserBalance(userId,icrVal);
            resMap.put("incrRest",res);
        } else if(WebUserCachTypeEnum.HefanTotal_type.getType() == cachType) {
            int res = webUserService.icrWebUserHefanTotal(userId,icrVal);
            resMap.put("incrRest",res);
        }

        WebUser webUser =  webUserService.findMyUserInfo(userId);
        resMap.put("webUser",webUser);
        return resMap;
    }
    public Integer getToClubIndex(String userId){
        return userCacheService.getToClubIndex(userId);
    }

    public void setToClubIndex(String userId){
        userCacheService.setToClubIndex(userId);
    }


}
